<template>
  <div>
    <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-area="changeArea"
    />
  </div>
</template>

<script setup>
import { Toast } from "vant";
import { areaList } from "@vant/area-data";
import { getAddress, editAddress, delAddress } from "@/api";
import { ref, onMounted } from "vue";
import useShopStore from "@/store/shop";
const shopStore = useShopStore();
import { useRouter, useRoute } from "vue-router";
const $router = useRouter();
const $route = useRoute();
const addressInfo = ref({});
const areaCode = ref("");

const changeArea = (value) => {
  areaCode.value = value.map((item) => item.code).join("-");
};

const onSave = async (value) => {
  value.country = value.county;
  value.areaCode = areaCode.value;
  let data = await editAddress($route.params.id, value);
  let { status, message } = data;
  if (!status) {
    $router.back();
  }
  Toast(message);
  let result = await getAddress();
  result.forEach((item) => {
    if (item.id === shopStore.address.id) {
      shopStore.setAddress(item);
    }
  });
};

const onDelete = async () => {
  let data = await delAddress($route.params.id);
  let { status, message } = data;
  if (!status) {
    $router.back();
  }
  Toast(message);
  // 删除再获取地址列表进行判断
  let addresslist = await getAddress();
  // 如果地址列表为空，就清空Vuex中的地址
  if (addresslist.length === 0) {
    shopStore.setAddress([]);
    return;
  }
  if (shopStore.address.id !== addressInfo.value.id) {
    return;
  }

  // 如果删除的地址是Vuex里面的地址，就取默认的地址存放到Vuex，如果没有默认地址就取第一个地址存到Vuex
  let defaultAddress = addresslist.filter((item) => {
    return item.isDefault == true;
  });
  if (defaultAddress.length > 0) {
    shopStore.setAddress(defaultAddress[0]);
  } else {
    shopStore.setAddress(addresslist[0]);
  }
};

onMounted(async () => {
  let data = await getAddress();
  let result = data.filter((item) => {
    return item.id == $route.params.id;
  });
  areaCode.value = result[0].areaCode;
  result[0].county = result[0].country;
  result[0].areaCode = result[0].areaCode.split("-")[2];
  addressInfo.value = result[0];
});
</script>
